﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace RedBlueBalls
{
    class RedFreq
    {
        private static bool analyzed = false;
        private static bool checkBest = false;
        private static int DEPTH = 10;
        private static int RED_SIZE = 34;
        private static int MIN_SUM = 10;
        private static int MAX_SUM = 15;
        private static int[] reds = new int[RED_SIZE];
        private static int RED_BALL = 6;

        public static void analyze(RedBlueBallRecord[] records)
        {
            // This code is used to check the best value
            if (checkBest)
            {
                for (int i = records.Length - 1; i > DEPTH; i--)
                {
                    int[] counts = new int[RED_BALL];
                    int[] balls = records[i].GetReds();
                    for (int j = 0; j < DEPTH; j++)
                    {
                        RedBlueBallRecord previous = records[i - j - 1];
                        for (int k = 0; k < RED_BALL; k++)
                            if (previous.HasRedBall(balls[k]))
                                counts[k]++;
                    }
                    Util.SortAsc(counts, RED_BALL);
                    StringBuilder sb = new StringBuilder();
                    int sum = 0;
                    sb.Append("Record ").Append(i).Append(": ");
                    for (int j = 0; j < RED_BALL; j++)
                    {
                        sb.Append(counts[j]).Append(" ");
                        sum += counts[j];
                    }
                    sb.Append(sum);
                    Tracer.AppendMessage(sb.ToString());
                }
            }

            for (int i = 0; i < RED_SIZE; i++)
                reds[i] = 0;

            int size = records.Length - 1;

            for (int i = 0; i < DEPTH; i++)
            {
                RedBlueBallRecord record = records[size-i];
                foreach (int red in record.GetReds())
                {
                    reds[red]++;
                }
            }

            for (int i = 1; i < RED_SIZE; i++)
                Tracer.AppendMessage(String.Format("Red {0} Frequence: {1}", i, reds[i]));

            analyzed = true;
        }

        public static bool predict(RedBlueBallRecord candidate)
        {
            if (!analyzed)
            {
                Tracer.AppendMessage("Please analyze the data first!");
                return false;
            }

            int[] balls = candidate.GetReds();
            int sum = 0;
            for (int i = 0; i < RED_BALL; i++)
                sum += reds[balls[i]];
            if (sum < MIN_SUM || sum > MAX_SUM)
                return false;

            return true;
        }
    }
}
